<?php

/*
 * Camelot PHP Tools
 *
 * @version 2.0
 * @author Bendsoft
 * @package PHP Tools
 * @subpackage Camelot
 * @license FreeBSD License (www.bendsoft.com/licensing/)
 *
 */

/**
 * Class to handle the UploadFile method in the Camelot WCF Service
 *
 * @author Bendsoft
 * @deprecated since version 2.0
 */
class CamelotUploadFile {

    /**
     * Success state of the transfer
     * @deprecated since version 2.0
     * @var bool 
     */
    public $result;

    /**
     * Message from the class
     * @deprecated since version 2.0
     * @var string 
     */
    public $message;

    /**
     * Constructor
     * @param Array $args 
     * @deprecated since version 2.0
     */
    function __construct($args) {
        /**
         * $args
         * file - the $_FILES object
         * folder - optional, if not stated we put the file in the root of the document library
         * listName - which document library
         * connectionString - the connectionstring we are supposed to use in the wcf service
         */
        // Validate required input parameters
        if (!array_key_exists("file", $args))
            die('msg:600');

        if (!array_key_exists("listName", $args))
            die('msg:605');

        if (!array_key_exists("connection_name", $args))
            die('msg:606');


        // Validate uploaded file
        if ($this->validate_file($args["file"])) {
            // Everything seems fine, so lets try to upload it to SharePoint
            $upload_file = $this->upload_file($args);
            if ($upload_file === true) {
                $this->result = true;
                $this->message = "Your file was successfully uploaded to SharePoint";
            } elseif ($upload_file === false) {
                $this->result = false;
                $this->message = "Your file could not be uploaded to SharePoint";
            } else {
                $this->result = $upload_file;
                $this->message = "Your file could not be uploaded because of a server or script error. Is the Camelot WCF Service really up and running?";
            }
        }
    }

    /**
     * Method to validate the uploaded file
     * 
     * @param array $file
     * @deprecated since version 2.0
     * @return boolean 
     */
    private function validate_file($file) {

        $file = $file["file"];

        // Check for errors
        if ($file["error"] > 0) {
            die('msg:604 (' . $file["error"] . ' - see http://php.net/manual/en/features.file-upload.errors.php)');
        }

        // Check valid file types
        if (constant("FILE_TYPES") != "*") {
            // Get file extension
            $ext = pathinfo($file["name"], PATHINFO_EXTENSION);

            // Turn valid file types into an array
            $valid_extensions = explode(",", constant("FILE_TYPES"));

            // If not found...
            if (!in_array(strtolower($ext), array_map('strtolower', $valid_extensions))) {
                die('msg:602');
            }
        }

        // File size checks
        // ...check the file is larger than zero
        if (!$file["size"] > 0) {
            die('msg:603');
        }

        // ...check max size
        if (constant("FILE_SIZE") != "*") {
            // If bigger than the allowed maximum
            if ($file["size"] > (int) constant("FILE_SIZE")) {
                die('msg:601');
            }
        }

        // Add more validation methods if required...

        return true;
    }

    /**
     * This method creates a connection to the WCF service and uploads the file
     * 
     * @param array $args
     * @deprecated since version 2.0
     * @return boolean or string 
     */
    private function upload_file($args) {
        $file = $args["file"]["file"];

        // Get the byte array from the file
        $byteArr = file_get_contents($file['tmp_name']);

        // Get the connection settings from the WcfSettingsList
        $WcfSettingsList = WcfSettingsList::instance();
        $settings = $WcfSettingsList->getSettings($args['connection_name']);

        if (is_null($settings)) {
            die('msg:800');
        }

        try {
            // Set up connection to WSDL Client
            $client = new CamelotSoapClient($settings);

            $folder = (isset($args["folder"])) ? $args["folder"] : "";

            $args = array(
                'listName' => $args["listName"],
                'file' => $folder . $file["name"],
                'data' => $byteArr,
                'connectionString' => $settings->connection_string,
                'sharedKey' => $settings->wsdl_shared_key
            );

            // Send file to WCF service and store result
            $uploadFile = $client->client->UploadFile($args)->UploadFileResult;

            if ($uploadFile == 1) {
                // If success
                return true;
            } else {
                // If fail
                return false;
            }
        } catch (Exception $exc) {
            // if we had a script error
            pr($exc);
            die;
            //return($exc->getTraceAsString());
        }
    }

}

/**
 * Class to handle the DownloadFile method in the Camelot WCF Service
 * 
 * @author Bendsoft
 * @deprecated since version 2.0
 */
class CamelotDownloadFile {

    /**
     * @var array
     */
    private $args;

    /**
     * Construct the class
     * @deprecated since version 2.0
     * @param array $args 
     */
    function __construct($args) {
        /**
         * $args
         * file - the file to download
         * listName - which document library
         * connectionString - the connectionstring we are supposed to use in the wcf service
         * type - which type of download, either FILE or INFOPATH. Defaults to FILE
         * version - which version of the file as a double. Defaults to the latest version
         */
        // Validate required input parameters
        if (!array_key_exists("file", $args))
            die('msg:700');

        if (!array_key_exists("listName", $args))
            die('msg:701');

        if (!array_key_exists("connection_name", $args))
            die('msg:702');

        $this->args = $args;
    }

    /**
     * Download the file set by the constructor, only by external call
     * @deprecated since version 2.0
     * @return void
     */
    function download_file() {

        // Get the connection settings from the WcfSettingsList
        $WcfSettingsList = WcfSettingsList::instance();
        $settings = $WcfSettingsList->getSettings($this->args['connection_name']);
        if (is_null($settings)) {
            die('msg:800');
        }

        try {
//            $wsdloptions = array(
//                'soap_version' => $settings->wsdl_soap_version,
//                'exceptions' => $settings->wsdl_exceptions,
//                'trace' => $settings->wsdl_trace
//            );
            // Open connection to the WCF service
            //$client = new SoapClient($settings->wsdl_address, $wsdloptions);
            // Set up connection to WSDL Client
            $client = new CamelotSoapClient($settings);


            // Handle the overload arguments
//            $overloadArgs = array(
//                'type' => $args["type"] == null ? 'file' : $args["type"],
//                'version' => $args["version"] == null ? '' : $args["version"]
//            );

            $args = array(
                'listName' => $this->args["listName"],
                'file' => $this->args["file"],
                'connectionString' => $settings->connection_string,
                'sharedKey' => $settings->wsdl_shared_key,
                'compression' => $settings->compression,
                'overloadArgs' => ''
            );

            // Get downloaded file from WCF Service
            $downloadedFile = $client->client->DownloadFile($args)->DownloadFileResult;


            // Send the file to the browser
            //header("Content-type: " . $this->get_mime_type($this->args["file"]));
            header("Content-type: application/data");
            header('Content-Disposition: attachment; filename="' . $this->get_filename() . '"');
            header("Content-Description: PHP Generated Data");
            echo $downloadedFile;
        } catch (Exception $exc) {
            // if we had a script error
            die("msg:703 <br />\n" . $exc->getTraceAsString());
        }
    }

    /**
     * 
     * @deprecated since version 2.0
     * @return type
     */
    function download_file_to_server() {

        // Get the connection settings from the WcfSettingsList
        $WcfSettingsList = WcfSettingsList::instance();
        $settings = $WcfSettingsList->getSettings($this->args['connection_name']);
        if (is_null($settings)) {
            die('msg:800');
        }

        try {
//            $wsdloptions = array(
//                'soap_version' => $settings->wsdl_soap_version,
//                'exceptions' => $settings->wsdl_exceptions,
//                'trace' => $settings->wsdl_trace
//            );
            // Open connection to the WCF service
            //$client = new SoapClient($settings->wsdl_address, $wsdloptions);
            // Set up connection to WSDL Client
            $client = new CamelotSoapClient($settings);

            $args = array(
                'listName' => $this->args["listName"],
                'file' => $this->args["file"],
                'connectionString' => $settings->connection_string,
                'sharedKey' => $settings->wsdl_shared_key,
                'compression' => $settings->compression
            );

            // Get downloaded file from WCF Service
            $downloadedFile = $client->client->DownloadFile($args)->DownloadFileResult;

            //$this->get_filename($this->args["file"]
            return $downloadedFile;
        } catch (Exception $exc) {
            // if we had a script error
            die("msg:703 <br />\n" . $exc->getTraceAsString());
        }
    }

    /**
     * Get the filename from serverurl, ie /Shared Documents/IMG_0338.jpg should return IMG_0338.jpg
     * @deprecated since version 2.0
     * @return string
     */
    private function get_filename() {
        $filePath = $this->args["file"];
        $filePathArray = explode("/", $filePath);
        $fileName = end($filePathArray);
        return $fileName;
    }

    /**
     * Get the mime type from file name
     * @param string $filename
     * @deprecated since version 2.0
     * @return mixed
     */
    private function get_mime_type($filename) {

        $fileext = substr(strrchr($filename, '.'), 1);

        if (empty($fileext)) {
            return (false);
        }

        $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext)/i";
        $lines = file("../mime.types", FILE_IGNORE_NEW_LINES);

        foreach ($lines as $line) {
            if (substr($line, 0, 1) == '#') {
                continue; // skip comments
            }

            if (!preg_match($regex, $line, $matches)) {
                continue; // no match to the extension
            }

            return ($matches[1]);
        }
        return (false);  // no match at all
    }

}

?>
